const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      isShare: 0
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,

    btnText: '立即报名',
    mySf: '',
    openid: '',
    shareTitle: '',
    shareImg: '',
    tipsContent: '',
    is_register: 0,
    id: 0,
    info: [],
    isOneShow: 1, //是否是第一次触发show
    is_cj_yy_my: 0, //抽奖预约是否满员
    my_is_yy: 0, //我是否预约了本次抽奖
    activeStatus: 0, //0:还未到预约时间 1:预约时间内 2：过了预约时间但抽奖未开始 3:抽奖中 4：既在预约又可抽奖状态 5:抽奖结束(抽奖时间已过)
    ylImgList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    var id = options.id;
    var is_share = options.is_share;

    if (id == '' || id == '0') {
      app.showTip('抱歉,未获取到相关的id信息哦');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        });
      }, 2000);
      return;
    }
    this.setData({
      id: id
    });


    //判断返回的跳转路径
    if (is_share == 1) {
      that.setData({
        ['defaultData.isShare']: 1
      });
    }

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getLotteryDrawDetailPageInfo(res.data.openid, id);

                //调用分享
                that.getShareInfo();
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //调用分享
      that.getShareInfo();

      //获取本页数据
      that.getLotteryDrawDetailPageInfo(openid, id);
    }
  },

  //获取本页数据
  getLotteryDrawDetailPageInfo(openid, id) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    })
    wx.request({
      url: that.data.baseUrl + 'getLotteryDrawDetailPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid,
        'id': id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          var html = that.formatRichText(res.data.info['content']);
          //重新赋值后台请求数据
          that.setData({
            is_register: res.data.is_register,
            mySf: res.data.mySf,
            info: res.data.info,
            html: html,
            tipsContent: res.data.tipsContent,
            is_cj_yy_my: res.data.is_cj_yy_my,
            my_is_yy: res.data.my_is_yy,
            activeStatus: res.data.activeStatus,
            ylImgList: res.data.ylImgList
          });

          //替换按钮文案
          if (res.data.info.activity_type == 2) {
            that.setData({
              btnText: '立即秒杀'
            });
          }

          //重置分享标题和描述         
          that.setData({
            shareTitle: res.data.info.title,
            shareImg: that.data.baseUrl + 'admin/' + res.data.info.img_path
          })
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        }
      },
      fail: function () {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });
  },


  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },


  //跳转下一页面
  appointTap() {
    var that = this;
    if (that.data.is_register == '0') {
      wx.showModal({
        title: '温馨提示',
        content: that.data.tipsContent,
        complete: (res) => {
          if (res.confirm) {
            //跳转注册界面
            wx.setStorageSync('loginHeaderUrl', '/pages/lotteryDrawPage/detail/index?id=' + that.data.id);
            wx.setStorageSync('loginHeaderType', 'redirectTo')
            if (res.confirm) {
              //跳转注册界面
              wx.redirectTo({
                url: '/pages/login/index'
              })
            }
          }
        }
      })
      return;
    } else {
      //活动 逻辑判断 报名身份
      if (that.data.info['is_bm'] == 1) {
        //报名权限满足
        var activeStatus = that.data.activeStatus;
        var my_is_yy = that.data.my_is_yy;
        var is_cj_yy_my = that.data.is_cj_yy_my;
        //判断此活动是抽奖还是秒杀
        if (that.data.info['activity_type'] == 1) {
          //逻辑判断
          if (activeStatus == 5 && my_is_yy == 0) {
            app.showTip('感谢您的参与,本次活动已经结束了哦');
            return;
          } else if (activeStatus == 0) {
            app.showTip('此活动还未开始预约哦');
            return;
          } else if (activeStatus == 2 && my_is_yy == 0) {
            app.showTip('您未预约本次活动哦');
            return;
          } else if (activeStatus == 3 && my_is_yy == 0) {
            app.showTip('您未预约本次活动哦');
            return;
          } else if (is_cj_yy_my == 1 && my_is_yy == 0) {
            app.showTip('本次活动预约已满员了哦');
            return;
          }
          //抽奖
          wx.navigateTo({
            url: '/pages/lotteryDrawPage/lotteryVideo/index?id=' + that.data.id
          });
        } else {
          var activeStatus = that.data.activeStatus;
          var my_is_yy = that.data.my_is_yy;
          if (activeStatus == 0) {
            app.showTip('此活动还未开始预约哦');
            return;
          } else if (activeStatus == 2 && my_is_yy == 0) {
            app.showTip('此活动预约时间已过哦');
            return;
          } else if (activeStatus == 3 && my_is_yy == 0) {
            app.showTip('您未预约本次活动哦');
            return;
          }
          if (activeStatus == 5 && my_is_yy == 0) {
            app.showTip('感谢您的参与,本次活动已经结束了哦');
            return;
          }
          //秒杀
          wx.navigateTo({
            url: '/pages/lotteryDrawPage/seckillCountdown/index?id=' + that.data.id
          });
        }
      } else {
        //没有报名权限
        app.showTip('抱歉,本活动仅限' + that.data.info.partake_sf + "参与哦");
        return;
      }
    }
  },

  //预览图片
  previewImage(e) {
    let that = this,
      imgsrc = that.data.ylImgList[0],
      arr = that.data.ylImgList
    wx.previewImage({
      current: imgsrc,
      urls: arr
    })
  },

  /**
   * 处理富文本里的图片宽度自适应
   * 1.去掉img标签里的style、width、height属性
   * 2.img标签添加style属性：max-width:100%;height:auto
   * 3.修改所有style里的width属性为max-width:100%
   * 4.去掉<br/>标签
   * @param html
   * @returns {void|string|*}
   */
  formatRichText(html) {
    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
      match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
      match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
      return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
      match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');
      return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    newContent = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin:10px 0;"');
    return newContent;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;

    if (that.data.isOneShow == 0) {
      //活动更新报名状态
      that.getLotteryDrawDetailPageInfo(that.data.openid, that.data.id);
    } else {
      that.setData({
        isOneShow: 0
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;

    return {
      title: that.data.shareTitle,
      path: '/pages/lotteryDrawPage/detail/index?id=' + that.data.id + '&is_share=1',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})